/**
 * Description:
 * Class Name:SynchronizedAccount
 * Date:2022/5/6 15:54
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第16章_多线程._16_5_同步线程._16_5_3_同步方法;

import 疯狂Java讲义.第16章_多线程._16_5_同步线程._16_5_1_线程安全问题之银行取钱问题.Account;

public class SynchronizedMethodAccount {
    // 封装账户编号、账户余额的两个成员变量
    private String accountNo;
    private double balance;
    public SynchronizedMethodAccount(){}
    public SynchronizedMethodAccount(String accountNo, double balance){
        this.accountNo = accountNo;
        this.balance = balance;
    }

    public double getBalance() {
        return balance;
    }

    public String getAccountNo() {
        return accountNo;
    }

    // 因为账户余额不允许随便修改，所以不为balance提供setter方法
    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Account account = (Account) o;
        return account.getAccountNo().equals(getAccountNo());
    }

    @Override
    public int hashCode() {
        return accountNo.hashCode();
    }

    public synchronized void draw(double drawAmount){
        // 账户余额大于取钱数目，则可取钱
        if (balance >= drawAmount){
            // 吐出钞票
            System.out.println("取钱成功！吐出钞票：" + drawAmount + " 元");
            try {
                Thread.sleep(1);
            }
            catch (InterruptedException e){
                e.printStackTrace();
            }
            // 修改余额
            balance -= drawAmount;
            System.out.println("\t余额为：" + balance);
        }
        else {
            System.out.println(Thread.currentThread().getName() + " 抱歉，余额不足！");
        }
    }
}
